# -*- coding: utf-8 -*-
"""
Created on Thu Jan  4 22:30:31 2024

@author: 28723
"""

import requests
import pandas as pd
import time
import json
import re

code = 'sh000985'
t = time.time()
random_timestamp = (int(round(t * 1000)))

params = {
    'cb': 'jQuery3510058714785687956184_1704550889679',
    'secid': '1.' + code[2:],
    'ut': 'fa5fd1943c7b386f172d6893dbfba10b',
    'fields1': 'f1,f2,f3,f4,f5,f6',
    'fields2': 'f51,f52,f53,f54,f55,f56,f57,f58,f59,f60,f61',
    'klt': 101,
    'fqt': 1,
    'end': 20500101,
    'lmt': 120,
    '_': random_timestamp,
}

init_url = 'https://push2his.eastmoney.com/api/qt/stock/kline/get'

r = requests.get(url=init_url, params=params, timeout=30)
content = r.content
content = content.decode()

content = re.sub(r'\s', '', content)
content = re.findall(r'\(({.*})\);', content)[0]
js_content = json.loads(content)

data = js_content['data']
klines = data['klines']
klines = [k.split(',') for k in klines]

col = ['交易日期', '开盘价', '收盘价', '最高价', '最低价', '成交量', '成交额', '振幅%', '涨跌幅%', '涨跌额', '换手率%']
df = pd.DataFrame(klines, columns=col)

df['股票代码'] = data['code'] 
df['股票名称'] = data['name']
df.to_csv('data/' + code + '.csv', index=False, encoding='gbk') 





















